// 画图模块
dojo.require("dojox.gfx");
// 移动模块
dojo.require("dojox.gfx.Moveable");
dojo.require("dojo.request.script");

// 全局的步骤
var GloblSteps = [];

// 申明了hrk.graph Class, 申明之后就可以给CLass添加属性了
dojo.declare("hrk.graph", null, {
    // 操作模式
    optMode:{pan:0,select:1,measure:2,mark:3},
    // G层图像对象
    G:null,
    // 如果元素包含devId,将会被保存下来
    devGraphMap:null,
    // 加载需要执行的函数    例如显示特定的地方
    _addOnLoadFuncitons:null,
    // 保存了 id 和 图像对象
    elements:null,
    // 被选择的元素
    selectElements:null,
    // 鼠标
    myCursors:{move:"default",moving:"url(http://192.168.1.158:8080/hrkweb_war/icons/closedhand.cur),move",ruler:"url(http://192.168.1.158:8080/hrkweb_war/icons/ruler.cur),default"},
    //当前操作模式
    currentOptMode:null,
    constructor:function(params){
        // 把params也一起放到 对象中
        dojo.safeMixin(this, params);
        this.devGraphMap = [];
        this.selectElements = [];
        this.currentOptMode = this.optMode.pan;
        this._addOnLoadFuncitons = [];
        document.addEventListener("contextmenu", this.preventWindowContextMenu, false);
        return this;
    },
    // 禁止用户右击,出菜单
    preventWindowContextMenu:function(e){
        e.preventDefault();
    },
    startup:function(){
        var my = this;
        require(["dojo/request/script"], function(script) {
            // 添加了一个div
            my._initInnerContainer();
            // 加载工具框
            my._initToolPanel();
            // 显示一直加载  添加了loadingdiv 指向
            my._addLoading();
            //发送请求
            dojo.xhrGet({
                url: 'http://localhost:63342/dojo/untitled/1.xml',
                content: {
                    picId:my.picId,
                    issbbm:my.issbbm,
                    rd:new Date()
                },
                handleAs: "text",
                load: function(d,io){
                    if(d==''){
                        d = '<G w="800" x="0" y="0" h="600" bgc="255,255,255" name="" bgi=""><Layer type="0" id="0" name="" show="1">'
                            +'<text AF="" fm="1" w="200" fs="32" x="320" y="200" ts="图形不存在" lc="0,0,0" wm="1" AssPlag="0" RowInterval="1" MatrixFontFlag="0" FontDeltaX="0" FontDeltaY="0" OutUid="72351848" FatherObj="" RoundBox="200.833333,859.600000,141.000000,48.000000" SwitchApp="1" tfr="rotate(0.000000) scale(1.000000, 1.000000)" Plane="0" fc="0,0,0" LevelEnd="0" ls="1" h="48.000000" ff="宋体" FontInterval="1" lw="1"/>'
                            +'</Layer></G>';
                    }
                    // 获取到svg 格式数据
                    var xmlDoc = new DOMParser().parseFromString(d, "text/xml").documentElement;
                    console.log(xmlDoc.constructor);
                    var G = new hrk.graph.G();
                    G.graph = my;
                    G.parse(xmlDoc);
                    my.G = G;
                    my.loaded = true;
                    /**
                     * my.container 指的是Map
                     * 一个div的id
                     */
                    my.renderTo(my.container);
                    document.getElementById(my.container).ref = my;
                    my._removeLoading();
                    for(var i=0;i<my._addOnLoadFuncitons.length;i++){
                        var func = my._addOnLoadFuncitons[i];
                        if(typeof(func) == 'function'){
                            func(my);
                        }
                    }
                    // my.loadFlags();
                },
                error: function(text,io){alert('startup error:'+text);}
            });
        });
    },
    _initInnerContainer:function(){
        var toolbarBox = {h:0};//dojo.contentBox(document.getElementById("titlePane"));
        var container = document.getElementById(this.container);
        // 在Map里面创建了一个div
        var innerContainer = document.createElement('div');
        this.innerContainer = innerContainer;
        innerContainer.style.top = toolbarBox.h + "px";
        innerContainer.style.left = '0px';
        innerContainer.style.width = '100%';
        innerContainer.style.height = '100%';
        innerContainer.style.position = 'relative';
        innerContainer.style.overflow = 'hidden';
        container.appendChild(innerContainer);
    },
    _initToolPanel:function(){
        /*var tp = new hrk.graph.ToolPanel({});
        tp.appendTo(this);*/
        var my = this;
        setTimeout(function(){
            var tp = new hrk.graph.ToolPanel({
                hrkgraph:my
            });
            if(document.getElementById(my.container).currentOptMode == 'select'){
            }
        },500);
    },
    // 获取元素的左上角 x,y 坐标
    _getAbsPosition:function(dom){
        if(dom.getBoundingClientRect){
            var body = document.compatMode == 'CSS1Compat'?document.documentElement:document.body;
            var box = dom.getBoundingClientRect();
            return {x : box.left + body.scrollLeft, y : box.top + body.scrollTop};
        }else{
            var x = y = 0;
            var p = dom;
            // p.offsetParent 返回一个指向最近的（指包含层级上的最近）包含该元素的定位元素或者最近的 table, td, th, body 元素
            while(p.offsetParent){
                // https://www.runoob.com/jsref/prop-element-offsetleft.html
                x += p.offsetLeft;
                y += p.offsetTop;
                p = p.offsetParent;
            }
            return {x:x, y:y};
        }
    },
    // 添加加载中效果
    _addLoading:function(){
        if(!this.loadingdiv){
            // 背景颜色
            this.loadingdiv = dojo.create('div');
            var div1 = dojo.create('div',{
                style:{
                    position: 'absolute',
                    width:'100%',
                    height:'100%',
                    zIndex:'99999',
                    background:'#CCC',
                    opacity:0.5
                }
            });
            // 加载图标
            var div2 = dojo.create('div',{
                style:{
                    position: 'absolute',
                    width:'100%',
                    height:'100%',
                    zIndex:'99999',
                    background:'transparent'
                },
                innerHTML:'<table width="100%" height="100%"><tr><td align="center"><img src="http://192.168.1.158:8080/hrkweb_war/images/loading.gif"><br><div style="font-size:20px;font-weight:bold;color:#000">加载中...</div></td></tr></table>'
            });
            this.loadingdiv.appendChild(div1);
            this.loadingdiv.appendChild(div2);
            dojo.byId(this.innerContainer).appendChild(this.loadingdiv);
        }else{
            this.loadingdiv.style.display = 'block';
        }
    },
    _removeLoading:function(){
        if(this.loadingdiv)
            this.loadingdiv.style.display = 'none';
    },
    // renderTo 进行画图的意思
    renderTo:function(){
        surface = this._createCanvas();
        this.onRender = function(){
            // 全部展示
            surface.setFullExtent();
        };
        this.G.renderTo(surface);
        this.onRender();
        var my = this;
        if(this.state == 1){
            setTimeout(function(){
                // my.setRTState();
            }, 1500);
        }else if(this.state == 2){
            setTimeout(function(){
                // my.setTopoState();
            }, 1500);
        }
        // my._askRtData();
    },
    // 创建画布 返回一个组  并且绑定事件
    _createCanvas:function(){
        var my = this;
        var graph = this;
        var toolbarBox = {h:0};//dojo.contentBox(document.getElementById("titlePane"));
        // map div
        var container = my.innerContainer;//document.getElementById(this.container);
        // 创建一个绘画的div
        surfaceHolder = document.createElement('div');
        this.surfaceHolder = surfaceHolder;
        surfaceHolder.style.width = '100%';
        surfaceHolder.style.height = '100%';
        container.appendChild(surfaceHolder);

        // 创建一个画布对象
        var surface = dojox.gfx.createSurface(surfaceHolder, "100%", "100%");//box.w,box.h
        // 创建一个组对象
        var group = surface.createGroup();
        // 是否是根
        group.isRoot = true;
        // 基础倍数
        group.baseScale = 1;
        // 倍数的比例
        group.scaleNumber = 0;
        // 先前的范围
        group.preExtent = [];
        // 获取中心点
        group.getCenterPoint = function(){
            var box = dojo.contentBox(surfaceHolder);
            var m = group.getTransform();
            return m==null?{x:box.w/2,y:box.h/2}:{x:(box.w/2)*m.xx+m.dx,y:(box.h/2)*m.yy+m.dy};
        };
        group.getScale = function(){
            var a=group.baseScale,b=(group.scaleNumber>0)?1.25:0.8;
            // abs 获取绝对值
            var c=Math.abs(group.scaleNumber);
            for(var i=0;i<c;i++){
                a = a*b;
            }
            return a;
        };
        // 设置全屏的范围
        group.setFullExtent = function(){
            // 如果G层有 宽度
            if(graph.G.w){
                // 设置范围
                group.setExtent(0,0,graph.G.w,graph.G.h);
            } else{
                // 使用Layer
                for(var i=0,lg = graph.G.children.length;i<lg;i++){
                    var l = graph.G.children[i];
                    if(l instanceof hrk.graph.Layer){
                        group.setExtent(0,0,l.w,l.h);
                        break;
                    }
                }
            }
            // 去除所有的显示范围
            while(group.preExtent.length > 0)
                group.preExtent.pop();
        };
        // 设置显示的范围
        group.setExtent = function(){
            // 传递一个对象,或者传递四个参数
            var xmin,ymin,xmax,ymax;
            if(arguments.length == 1){
                xmin = arguments[0].xmin;
                ymin = arguments[0].ymin;
                xmax = arguments[0].xmax;
                ymax = arguments[0].ymax;
            }
            else if(arguments.length == 4){
                xmin = arguments[0];
                ymin = arguments[1];
                xmax = arguments[2];
                ymax = arguments[3];
            }
            var box = dojo.contentBox(surfaceHolder);
            var hs = box.w/(xmax-xmin)>box.h/(ymax-ymin);
            var s = group.baseScale = !hs?box.w/(xmax-xmin):box.h/(ymax-ymin);
            group.scaleNumber = 0;
            var dx = hs?(box.w-(xmax-xmin)*s)/2-xmin*s:-xmin*s;
            var dy = hs?-ymin*s:(box.h-(ymax-ymin)*s)/2-ymin*s;
            group.setTransform({xx:s,yy:s,dx:dx,dy:dy});
            graph.onScale(group.getScale());
        };
        // 中间放大
        group.centerAndZoom = function(idx){
            var box = dojo.contentBox(surfaceHolder);
            var s0 = group.getScale();
            group.scaleNumber += idx;
            var s = group.getScale();
            var m = group.getTransform();
            m=m?m:{xx:1,yy:1,xy:0,yx:0,dx:0,dy:0};
            var dx = (m.dx - (1-s0)*box.w/2)*s/s0;
            var dy = (m.dy - (1-s0)*box.h/2)*s/s0;
            group.setTransform({xx:s,yy:s,dx:(1-s)*box.w/2+dx,dy:(1-s)*box.h/2+dy});
            graph.onScale(group.getScale());
        };
        // 鼠标的三种操作  draging  拖曳    zooming 缩放   selecting 选择
        var MouseOperation = {none:0,draging:1,zooming:2,selecting:3};
        var curMosOpt = MouseOperation.none;
        //
        var bxy={};
        //  创建一个div 用于放大或者选取
        var g_opt_rect = document.createElement('div');
        g_opt_rect.style.border = "dashed 2px #FFEBB1";
        g_opt_rect.style.background = "#90BBE4";
        g_opt_rect.style.opacity = 0.5;
        g_opt_rect.style.top = '0px';
        g_opt_rect.style.left = '0px';
        g_opt_rect.style.width = '0px';
        g_opt_rect.style.height = '0px';
        g_opt_rect.style.display = "none";
        g_opt_rect.style.position = 'absolute';
        document.body.appendChild(g_opt_rect);

        dojo.connect(surfaceHolder,'onmousedown',function(e){
            surfaceHolder.absPos = my._getAbsPosition(surfaceHolder);
            e.preventDefault();
            my._setCapture(surfaceHolder);
            if(e.shiftKey){
                curMosOpt = MouseOperation.zooming;
                g_opt_rect.x = e.clientX;
                g_opt_rect.style.left = e.clientX + "px";
                g_opt_rect.y = e.clientY;
                g_opt_rect.style.top = e.clientY + "px";
                g_opt_rect.style.display = "block";
            }else if(e.ctrlKey){
                // ctrl 切换成移动的模式
                curMosOpt = MouseOperation.draging;
                // 改变鼠标的样式
                surfaceHolder.style.cursor=my.myCursors.moving;
            }
            else if(my.currentOptMode == my.optMode.pan){// || e.button==2){
                curMosOpt = MouseOperation.draging;
                surfaceHolder.style.cursor=my.myCursors.moving;
            }
            else if(my.currentOptMode == my.optMode.select){
                curMosOpt = MouseOperation.selecting;
                g_opt_rect.x = e.clientX;
                g_opt_rect.style.left = e.clientX + "px";
                g_opt_rect.y = e.clientY;
                g_opt_rect.style.top = e.clientY + "px";
                g_opt_rect.style.display = "block";
            }
            bxy.x = e.clientX;//e.clientX - p.x;
            bxy.y = e.clientY;//e.clientY - p.y;
        });
        dojo.connect(document.body,'onmouseup',function(e){
            e.preventDefault();
            my._releaseCapture(surfaceHolder);
            if(curMosOpt == MouseOperation.zooming){
                var edx = e.clientX - surfaceHolder.absPos.x,
                    edy = e.clientY - surfaceHolder.absPos.y,
                    stx = bxy.x - surfaceHolder.absPos.x,
                    sty = bxy.y - surfaceHolder.absPos.y;
                // 上左 上右 下左 下右  四种操作方式
                if(e.clientX > bxy.x && e.clientY > bxy.y){
                    var m = group.getTransform();
                    edx = (edx - m.dx) / m.xx;
                    edy = (edy - m.dy - toolbarBox.h) / m.yy;
                    stx = (stx - m.dx) / m.xx;
                    sty = (sty - m.dy - toolbarBox.h) / m.yy;
                    // 设置查看的窗口
                    group.setExtent(stx,sty,edx,edy);
                    // 记录下当前查看的窗口
                    group.preExtent.push({xmin:stx,ymin:sty,xmax:edx,ymax:edy});
                    if(group.preExtent.length > 10)
                        group.preExtent.shift();
                }
                else if(e.clientX < bxy.x && e.clientY > bxy.y){

                }
                else if(e.clientX < bxy.x && e.clientY < bxy.y){
                    group.preExtent.pop();
                    if(group.preExtent.length > 0){
                        group.setExtent(group.preExtent[group.preExtent.length - 1]);
                    }
                    else
                        group.setFullExtent();
                }
                else{

                }
            }else if(curMosOpt == MouseOperation.selecting){
                var x = e.clientX - surfaceHolder.absPos.x;
                var y = e.clientY - surfaceHolder.absPos.y;
                bxy.x = bxy.x - surfaceHolder.absPos.x;
                bxy.y = bxy.y - surfaceHolder.absPos.y;
                if(x==bxy.x && y==bxy.y){
                    var m = group.getTransform();
                    var edx = (x - m.dx) / m.xx;
                    var edy = (y - m.dy - toolbarBox.h) / m.yy;
                    graph.onSelect([edx,edy]);
                    /**
                     * 0：主按键，通常指鼠标左键或默认值（译者注：如 document.getElementById('a').click() 这样触发就会是默认值）
                     * 1：辅助按键，通常指鼠标滚轮中键
                     * 2：次按键，通常指鼠标右键
                     * 3：第四个按钮，通常指浏览器后退按钮
                     * 4：第五个按钮，通常指浏览器的前进按钮
                     */
                    if(e.button==2){
                        if(graph.selectElements.length != 0){
                            var ele = graph.selectElements[0];
                            if(ele.DevID && ele.DevTypeId){
                                new com.hrk.js.device.DevMenu({
                                    module:'graph',//可选值devtree,graph
                                    graph:my,
                                    devId : ele.DevID,
                                    devIdType : 1,
                                    devType : ele.DevTypeId,
                                    position: [e.x,e.y], //[p.x, p.y] or {x:p.x,y:p.y} or [p.x,p.y]
                                    localToPic:function(devId, picId){
                                        GloblSteps.push(my.picId);
                                        document.getElementById(my.container).innerHTML = "";
                                        //创建一个单线图实例
                                        var graph = new hrk.graph({
                                            container:my.container,
                                            picId:picId,
                                            currentOptMode:1});
                                        if(devId){
                                            graph.addOnLoad(function(g){
                                                g.localTo(devId);
                                            });
                                        }
                                        graph.startup();
                                    }
                                });
                            }
                        }
                    }
                }else{
                    var m = group.getTransform();
                    var sdx = (bxy.x - m.dx) / m.xx, sdy = (bxy.y - m.dy - toolbarBox.h) / m.yy;
                    var edx = (x - m.dx) / m.xx, edy = (y - m.dy - toolbarBox.h) / m.yy;
                    graph.onSelect([Math.min(sdx,edx),Math.min(sdy,edy),Math.max(sdx,edx),Math.max(sdy,edy)]);
                }
            }
            g_opt_rect.style.width = "0px";
            g_opt_rect.style.height = "0px";
            g_opt_rect.style.display = "none";
            curMosOpt = MouseOperation.none;
            my.setCurrentMapCursor();
        });
        dojo.connect(document.body,'onmousemove',function(e){
            e.preventDefault();
            //my._setCapture(surfaceHolder);
            if(curMosOpt == MouseOperation.draging){
                var m = group.getTransform();
                // xx 就是x坐标  yy 就是y坐标  这里已经进行移动了
                m?group.setTransform({xx:m.xx,yy:m.yy,dx:e.clientX-bxy.x+m.dx,dy:e.clientY-bxy.y+m.dy})
                    :group.setTransform({dx:e.clientX-bxy.x,dy:e.clientY-bxy.y});
                // 记录下当前的鼠标位置
                bxy.x = e.clientX;
                bxy.y = e.clientY;
                for(var i=0;i<graph.charts.length;i++){
                    graph.charts[i].onScale(m.xx);
                }
            }
            else if(curMosOpt == MouseOperation.zooming){
                g_opt_rect.style.left = ((e.clientX - bxy.x>0)?bxy.x:e.clientX) + "px";
                g_opt_rect.style.width = Math.abs(e.clientX - bxy.x) + "px";
                g_opt_rect.style.top = ((e.clientY - bxy.y>0)?bxy.y:e.clientY) + "px";
                g_opt_rect.style.height = Math.abs(e.clientY - bxy.y) + "px";
                // 四个方块有有四种不同的功能
                if(e.clientX > bxy.x && e.clientY > bxy.y)
                    g_opt_rect.style.background = "url(http://192.168.1.158:8080/hrkweb_war/icons/nav_zoomin.png) center no-repeat #90BBE4";
                else if(e.clientX < bxy.x && e.clientY > bxy.y)
                    g_opt_rect.style.background = "url(http://192.168.1.158:8080/hrkweb_war/icons/delete.gif) center no-repeat #90BBE4";
                else if(e.clientX < bxy.x && e.clientY < bxy.y)
                    g_opt_rect.style.background = "url(http://192.168.1.158:8080/hrkweb_war/icons/arrow_undo.png) center no-repeat #90BBE4";
                else
                    g_opt_rect.style.background = "url(http://192.168.1.158:8080/hrkweb_war/icons/nav_zoomout.png) center no-repeat #90BBE4";
            }
            else if(curMosOpt == MouseOperation.selecting){
                g_opt_rect.style.left = ((e.clientX - bxy.x>0)?bxy.x:e.clientX) + "px";
                g_opt_rect.style.width = Math.abs(e.clientX - bxy.x) + "px";
                g_opt_rect.style.top = ((e.clientY - bxy.y>0)?bxy.y:e.clientY) + "px";
                g_opt_rect.style.height = Math.abs(e.clientY - bxy.y) + "px";
                g_opt_rect.style.background = "#90BBE4";
            }
        });
        // 滚轮事件,放大缩小
        function mousewheel(event){
            curMosOpt = MouseOperation.none;
            var e = event || window.event,eDir=0;		//设置滚轮事件,e.wheelDelta与e.detail分别兼容IE、W3C，根据返回值的正负来判断滚动方向
            if(e.wheelDelta) { eDir = e.wheelDelta/120; }
            else if(e.detail) { eDir = -e.detail/3; }
            eDir > 0 ? group.centerAndZoom(1):group.centerAndZoom(-1);
        };
        dojo.connect(surfaceHolder,'onmousewheel',mousewheel);
        dojo.connect(surfaceHolder,'onDOMMouseScroll',mousewheel);
        this.rootGroup = group;
        return group;
    },
    // 设置画笔的宽度
    onScale:function(scale){
        this.G.onScale(scale);
    },
    // 设置事件目标
    _setCapture:function(dom){
        if(dom.setCapture)
            dom.setCapture();
        else if(window.captureEvents){
            window.captureEvents(/*Event.MOUSEDOWN|*/Event.MOUSEMOVE|Event.MOUSEUP);
        }
    },
    // 去除事件目标
    _releaseCapture:function(dom){
        if(dom.releaseCapture)
            dom.releaseCapture();
        else if(window.releaseEvents){
            window.releaseEvents(/*Event.MOUSEDOWN|*/Event.MOUSEMOVE|Event.MOUSEUP);
        }
    },
    // 设置鼠标样式
    setCurrentMapCursor:function(){
        var s='default';
        switch(this.currentOptMode){
            case this.optMode.pan:
                s=this.myCursors.move;
                break;
            case this.optMode.select:
                s='default';
                break;
            /*case this.optMode.measure:
                s=this.myCursors.ruler;
                break;*/
            case this.optMode.mark:
                s='default';
                break;
            default:
                s='default';
                break;
        }
        surfaceHolder.style.cursor=s;
    },
    // 设置成选择模式
    setSelectMode:function(){
        // true和false来回切换
        this.toolPanel.btnSel.toggle(true,false);
        this.currentOptMode=this.optMode.select;
        this.setCurrentMapCursor();
        document.getElementById(this.container).currentOptMode = 'select';
    },
    // 设置成平移模式
    setPanMode:function(){
        this.toolPanel.btnPan.toggle(true,false);
        this.currentOptMode=this.optMode.pan;
        this.setCurrentMapCursor();
        document.getElementById(this.container).currentOptMode = 'pan';
    },
    zoom:function(n){
        if(n == 0)
            this.rootGroup.setFullExtent();
        else
            this.rootGroup.centerAndZoom(n);
    },
    onSelect:function(o){
        for(var i=0,c=this.selectElements.length;i<c;i++){
            //this.selectElements[i].unholdColor();
            this.selectElements[i]._holdState = 0;
            this.selectElements[i].setColorByState();
        }
        this.selectElements = [];
        this.G.trySelect(o);
    },
});
dojo.declare("hrk.graph._base", null, {
    // 图形对象
    _graphic:null,
    constructor:function(){
        this.children = [];
    },
    /**
     * 将标签的属性 解析成一个对象属性方法
     * @param name
     * @param type 默认string，可选int,float,bool,rgba
     */
    _setAttribute:function(name,type){
        var o = this._docElement.attributes.getNamedItem(name);
        if(o){
            switch(type){
                case 'int':
                    this[name] = parseInt(o.value);
                    break;
                case 'float':
                    this[name] = parseFloat(o.value);
                    break;
                case 'bool':
                    this[name] = o.value=='0'?false:true;
                    break;
                case 'point':
                    var vs = o.value.split(',');
                    this[name] = {x:parseFloat(vs[0]),y:parseFloat(vs[1])};
                    break;
                case 'roundbox':
                    var vs = o.value.split(',');
                    this[name] = {x:parseFloat(vs[0]),y:parseFloat(vs[1]),w:parseFloat(vs[2]),h:parseFloat(vs[3])};
                    break;
                case 'rgba':
                    if(o.value == 'transparent'){
                        this[name] = {show:true,r:0,g:0,b:0,a:0};
                        break;
                    }
                    var vs = o.value.split(',');
                    if(vs.length==0)break;
                    var att = this[name] = {show:true,r:0,g:0,b:0,a:1};
                    att.r = vs[0]?parseInt(vs[0]):0;
                    att.g = vs[1]?parseInt(vs[1]):0;
                    att.b = vs[2]?parseInt(vs[2]):0;
                    att.a = vs[3]?parseInt(vs[3]):this.alpha/255;
                    break;
                case 'tfr':
                    var rs = this[name] = {rotate:0,scale:[1.0,1.0]};
                    var s = o.value;
                    var idx=  s.indexOf('rotate(');
                    if(idx>=0){
                        s=s.substr(idx+7);
                        rs.rotate = parseInt(s.substring(0,s.indexOf(')')));
                    }
                    s = o.value;
                    idx=s.indexOf('scale(');
                    if(idx>=0){
                        s=s.substr(idx+6);
                        s=s.substring(0,s.indexOf(')')).split(',');
                        rs.scale =  [parseFloat(s[0]),parseFloat(s[1])];
                    }
                    break;
                case 'link':
                    var vs = o.value.split(';');
                    if(vs.length==0)break;
                    this[name] = [];
                    for(var i=0;i<vs.length;i++){
                        var ss = vs[i].split(',');
                        if(ss.length>=3){
                            this[name].push(ss[2]);
                            if(!this.graph.devCLineMap[ss[2]])
                                this.graph.devCLineMap[ss[2]] = [];
                            this.graph.devCLineMap[ss[2]].push(this);
                        }
                    }
                    break;
                default:
                    this[name] = o.value;
            }
        }
    },
    /**
     * 将一个dom文档 转换成对象 子类也是在这里就创建好了
     * @param docElement
     * @param replaceAttrs
     */
    parse:function(docElement, replaceAttrs){
        this._docElement = docElement;
        this.nodeName = docElement.nodeName;
        this._setAttribute('id');
        if(this.id && this._joinIDMap)
            this.graph.elements[this.id] = this;
        this._setAttribute('name');
        this._setAttribute('keyid');
        this._setAttribute('DevID','int');
        if(this['DevID']<=0)this['DevID']=null;
        this._setAttribute('DevTypeId','int');
        this._setAttribute('DevCategory','int');
        this._setAttribute('ls','int');
        this._setAttribute('lw','int');
        this._setAttribute('fm','int');
        this._setAttribute('alpha','int');
        this._setAttribute('lc','rgba');
        this._setAttribute('fc','rgba');
        this._setAttribute('tfr','tfr');
        this._setAttribute('sta');
        this._setAttribute('link','link');
        if(replaceAttrs){
            for(var a in replaceAttrs){
                this[a] = replaceAttrs[a];
            }
        }
        var nodes = this._docElement.childNodes;
        for(var i=0,lg=nodes.length;i<lg;i++){
            console.log("nodes[i].nodeType:" + nodes[i].nodeType);
            // nodeType 是xml的节点属性
            // 如果节点是一个元素节点，nodeType 属性返回 1。
            // 如果节点是属性节点, nodeType 属性返回 2。
            // 如果节点是一个文本节点，nodeType 属性返回 3。
            // 如果节点是一个注释节点，nodeType 属性返回 8
            if(nodes[i].nodeType != 1) {
                continue;
            }
            if(nodes[i].nodeName.toLowerCase() != 'layer' && nodes[i].nodeName.toLowerCase() != 'text') {
                continue;
            }
            var st = hrk.graph.SharpType[nodes[i].nodeName.toLowerCase()];
            var g;
            if(st && (g=hrk.graph[st])){
                var s = new g();
                s.graph = this.graph;
                s.parent = this;
                s.parse(nodes[i], replaceAttrs);
                this.children.push(s);
            }
            else{
                if(st)
                    hrk.graph.logger.push('图形'+st+'没有实现类定义');
                else
                    hrk.graph.logger.push('节点'+nodes[i].nodeName+'无对应图形定义');
            }
        }
        if(!(this instanceof hrk.graph.Rect)){
            var key = this.DevID;
            if(key){
                // 创建一个对象
                if(!this.graph.devGraphMap[key]){
                    this.graph.devGraphMap[key] = {val:null,objs:[],extend_objs:[]};
                }
                //
                this.graph.devGraphMap[key].objs.push(this);
            }
        }
    },
    // 缩放的时候需要进行的操作,有时候缩放到很小的时候 文本需要隐藏
    onScale:function(scale){
        for(var i=0,lg=this.children.length;i<lg;i++){
            this.children[i].onScale(scale);
        }
        if(!this._graphic)return;
        var s = this._graphic.getStroke();
        if(!s)return;
        var p = this;
        var innerscale = p.getScale();
        while(p.parent){
            p = p.parent;
            innerscale *= p.getScale();
        }
        if(!scale)
            scale = p._selfGroup.getScale();
        s.width = this.lw /(scale * innerscale);
        // 设置粗细
        this._graphic.setStroke(s);
    },
    // 画 子节点图形
    renderChildren:function(group){
        for(var i=0,lg=this.children.length;i<lg;i++){
            this.children[i].renderTo(group);
        }
    },
    // 获取缩放大小
    getScale:function(){
        if(!this.tfr)
            return 1.0;
        return this.tfr.scale[0];
    },
});
/**
 * 矩形
 */
dojo.declare("hrk.graph.Rect", [hrk.graph._base], {
    x:0,y:0,w:0,h:0,
    ShadowType:0,//矩形显示阴影的方式
});
/**
 * 顶层G
 */
dojo.declare("hrk.graph.G", [hrk.graph._base], {
    // 背景颜色
    bgc:{show:false,r:255,g:255,b:255,a:1},
    // 背景图片
    bgi:null,
    parse:function(docElement, replaceAttrs){
        // inherited 调用父类的 parse方法
        this.inherited(arguments, replaceAttrs);
        this._setAttribute('x','float');
        this._setAttribute('y','float');
        this._setAttribute('w','float');
        this._setAttribute('h','float');
        this._setAttribute('bgc','rgba');
        this._setAttribute('bgi');
        this._setAttribute('show','bool');
    },
    renderTo:function(group){
        if(this.bgc.show)
            this.graph.surfaceHolder.style.backgroundColor = "rgb("+this.bgc.r+","+this.bgc.g+","+this.bgc.b+")";
        if(this.bgi)
            this.graph.surfaceHolder.style.backgroundImage = 'url(../versionfiles/'+this.bgi.replace(/\\/g,'/')+')';
        this._sharpGroup = group;
        var rect = { x: this.x, y: this.y, width: this.w, height: this.h }; // 定义一个矩形
        this._selfGroup = group;
        this._graphic = this._selfGroup.createRect(rect);// 创建矩形
        // 开始画子类图像
        this.renderChildren(this._selfGroup);
    }
});

dojo.declare("hrk.graph.Layer", [hrk.graph._base], {
    _selfGroup:null,
    type:null,
    x:0,y:0,w:0,h:0,
    name:'',
    bgc:{show:false,r:0,g:0,b:0,a:1},
    bgi:null,
    show:true,
    parse:function(docElement){
        this.inherited(arguments);
        this._setAttribute('x','float');
        this._setAttribute('y','float');
        this._setAttribute('w','float');
        this._setAttribute('h','float');
        this._setAttribute('bgc','rgba');
        this._setAttribute('bgi');
        this._setAttribute('show','bool');
    },
    renderTo:function(group){
        this._sharpGroup = group;
        this._selfGroup = group.createGroup();
        this.renderChildren(this._selfGroup);
        if(!this.show)this.hide();
    },
    show:function(){
        if(this._sharpGroup == null)return;
        this._sharpGroup.add(this._selfGroup);
    },
    hide:function(){
        if(this._selfGroup == null)return;
        this._selfGroup.removeShape(false);
    }
});

/**
 * 文本
 */
dojo.declare("hrk.graph.Text", [hrk.graph._base], {
    x:0,y:0,wm:1,ff:'',fs:20,
    ts:'',//文本内容
    parse:function(docElement){
        this.inherited(arguments);
        this._setAttribute('x','float');
        this._setAttribute('y','float');
        this._setAttribute('wm','int');
        this._setAttribute('ff');
        this._setAttribute('fs','int');
        this._setAttribute('ts');
    },
    renderTo:function(group){
        this._sharpGroup = group;
        //if(this.sta != undefined && this.sta != 0)return;
        //图形文字大小小于6时显示会有问题，这里重新计算了文字大小
        var fs = this.fs, applyScale=this.tfr.scale;
        if(fs<10){
            fs = 10;
            applyScale[0] = applyScale[0] * this.fs / fs;
            applyScale[1] = applyScale[1] * this.fs / fs;
        }

        this._subgraphic = [];
        var subts = this.ts.split("\n");
        // 换行的话分开来
        for(var i=0;i<subts.length;i++){
            var _graphic = group.createText({x:this.x,y:this.y+fs+(fs*i),text:subts[i]});
            _graphic.setFont({family:this.ff,size:fs+'px'});
            if(this.lc.show)//this._graphic.setStroke({color: [this.lc.r, this.lc.g, this.lc.b, this.lc.a], width: this.lw, style:this._getLineStyle()});
                _graphic.setFill([this.lc.r, this.lc.g, this.lc.b, this.lc.a]);
            _graphic.applyTransform(dojox.gfx.matrix.rotategAt(this.tfr.rotate,this.x,this.y));
            var scale = applyScale;//this.tfr.scale;
            _graphic.applyTransform(dojox.gfx.matrix.scaleAt(scale[0],scale[1],this.x,this.y));
            this._subgraphic.push(_graphic);
        }
        var oo = this;
        // 暴露图形对象修改样式的方法
        this._graphic = {
            getFont:function(){
                return oo._subgraphic[0].getFont();
            },
            setFont:function(f){
                for(var i=0;i<oo._subgraphic.length;i++){
                    oo._subgraphic[i].setFont(f);
                }
            },
            getFill:function(){
                return oo._subgraphic[0].getFill();
            },
            getStroke:function(){
                return oo._subgraphic[0].getStroke();
            },
            setFill:function(c){
                for(var i=0;i<oo._subgraphic.length;i++){
                    oo._subgraphic[i].setFill(c);
                }
            },
            setStroke:function(c){
                for(var i=0;i<oo._subgraphic.length;i++){
                    oo._subgraphic[i].setStroke(c);
                }
            }
        };
    },
    // 显示和隐藏
    show:function(){
        if(this._sharpGroup == null)return;
        for(var i=0;i<this._subgraphic.length;i++){
            this._sharpGroup.add(this._subgraphic[i]);
        }
    },
    hide:function(){
        for(var i=0;i<this._subgraphic.length;i++){
            this._subgraphic[i].removeShape(false);
        }
    },
    // 缩放的时候需要进行的操作,有时候缩放到很小的时候 文本需要隐藏
    onScale:function(scale){
        if(!this._graphic)return;
        var p = this;
        var innerscale = p.getScale();
        console.log("innerscale:" + innerscale);
        console.log("scale:" + scale);
        console.log("p.parent:" + p.parent);
        while(p.parent){
            p = p.parent;
            innerscale *= p.getScale();
        }
        if(!scale)
            scale = p._selfGroup.getScale();
        if(this.fs * innerscale * scale < 5){
            this.hide();
        }else{
            this.show();
        }
    }
});


// 给Class添加属性
// 用于保存日志
hrk.graph.logger = [];
// 记录下所有的对象,通过字符串的方式创建对象
hrk.graph.SharpType = {
    line:'Line',rect:'Rect',roundrect:'RoundRect',circle:'Circle',ellipse:'Ellipse',circlearc:'CircleArc',ellipsearc:'EllipseArc',polyline:'Polyline',polygon:'Polygon',triangle:'Triangle',parallelrect:'ParallelRect',diamond:'Diamond',text:'Text',image:'Image',cube:'Cube',pin:'Pin',
    dtext:'DText',connectline:'ConnectLine',bus:'Bus',acline:'ACLine',aclineend:'ACLineEnd',qt:'QT',other:'Other',cbreaker:'CBreaker',disconnector:'Disconnector',grounddisconnector:'GroundDisconnector',generator:'Generator',transformer2:'Transformer2',transformer3:'Transformer3',energyconsumer:'EnergyConsumer',capacitor_p:'Capacitor_P',reactor_p:'Reactor_P',capacitor_s:'Capacitor_S',reactor_s:'Reactor_S',fuse:'Fuse',protect:'Protect',state:'State',status:'Status',token:'Token',terminal:'Terminal',ascoil:'Ascoil',arrester:'Arrester',gzp:'Gzp',pt:'PT',ct:'CT',powerflow:'PowerFlow',
    poke:'Poke',layer:'Layer',linechart:'LineChart'
};

Ext.define('hrk.graph.ToolPanel', {
    extend: 'Ext.panel.Panel',
    constructor: function (config) {
        if(!config.hrkgraph){
            alert('请设置\r工具栏控件(com.graph.ToolPanel)\r实例的hrkgraph参数。');
            return;
        }
        var my = this;
        config.hrkgraph.toolPanel = this;
        var div = dojo.create('div',{
            style:{"float":'left',"position":'absolute',"top":'0px',"right":'0px',"height":24,"width":480}
        });
        this.div = div;
        //
        dojo.byId(config.hrkgraph.innerContainer).appendChild(div);

        var btnDefaultCfg = {
            //cls: 'btn-custom',
            // 不加x-btn(baseCls属性)前缀 extjs通过addClsWithUI方法自动加
            //overCls:'btn-over-custom',
            //pressedCls:'btn-pressed-custom',
            scale: 'small'
        };
        this.btnPre = Ext.create('Ext.Button', Ext.Object.merge({
            text:'前幅',
            icon:'http://192.168.1.158:8080/hrkweb_war/icons/del-left.gif',
            disabled:GloblSteps<=0?true:false,
            handler: function(btn) {
                my.hrkgraph.pre();
            }
        },btnDefaultCfg));
        this.btnState = Ext.create('Ext.Button', Ext.Object.merge({
            //hidden:true,
            text:'图模态',
            menu:[{
                text:'图模态',
                handler: function() {
                    my.hrkgraph.setCommonState();
                }
            },{
                text:'实时态',
                handler: function() {
                    my.hrkgraph.setRTState();
                }
            },{
                text:'研判态',
                handler: function() {
                    my.hrkgraph.setTopoState();
                }
            }]
        },btnDefaultCfg));
        this.btnPan = Ext.create('Ext.Button', Ext.Object.merge({
            text:'平移',
            icon:'http://192.168.1.158:8080/hrkweb_war/icons/nav_pan.png',
            // 设置按钮是否按下
            pressed:config.hrkgraph.currentOptMode == config.hrkgraph.optMode.pan,
            // 一个组内只能有一个被选择
            toggleGroup:'panorsel',
            handler: function(btn) {
                //btn.toggle(true,true);
                my.hrkgraph.setPanMode();
            }
        },btnDefaultCfg));
        this.btnSel = Ext.create('Ext.Button', Ext.Object.merge({
            text:'选取',
            icon:'http://192.168.1.158:8080/hrkweb_war/icons/select.gif',
            // 设置按钮是否按下
            pressed:config.hrkgraph.currentOptMode == config.hrkgraph.optMode.select,
            toggleGroup:'panorsel',
            handler: function(btn) {
                //btn.toggle(true,true);
                my.hrkgraph.setSelectMode();
            }
        },btnDefaultCfg));
        this.btnZoomin = Ext.create('Ext.Button', Ext.Object.merge({
            text:'放大',
            icon:'http://192.168.1.158:8080/hrkweb_war/icons/nav_zoomin.png',
            handler: function() {
                my.hrkgraph.zoom(1);
            }
        },btnDefaultCfg));
        this.btnZoomout = Ext.create('Ext.Button', Ext.Object.merge({
            text:'缩小',
            icon:'http://192.168.1.158:8080/hrkweb_war/icons/nav_zoomout.png',
            handler: function() {
                my.hrkgraph.zoom(-1);
            }
        },btnDefaultCfg));
        this.btnZoomfull = Ext.create('Ext.Button', Ext.Object.merge({
            text:'全图',
            icon:'http://192.168.1.158:8080/hrkweb_war/icons/nav_fullextent.png',
            handler: function() {
                my.hrkgraph.zoom(0);
            }
        },btnDefaultCfg));
        var defaultCfg = {
            renderTo: div,
            border:false,
            width:400,
            height:24,
            bodyStyle:{
                background:'transparent'
            },
            layout: {
                type: 'hbox',
                //padding:'2',
                align : 'stretch'//stretch,middle
            },
            items: [this.btnPre,this.btnState,this.btnPan,this.btnSel,this.btnZoomin,this.btnZoomout,this.btnZoomfull]
        };
        config = Ext.Object.merge(defaultCfg, config);
        this.callParent(arguments);
    },
    setStateBtnCls:function(state){
        if(state == 0){
            this.btnState.setText("图模态");
        }else if(state == 1){
            this.btnState.setText("实时态");
        }else if(state == 2){
            this.btnState.setText("研判态");
        }
    }
});